<?php

class Maven_ManageCatalogSpr_Model_Mysql4_Temp_Price extends Mage_Core_Model_Mysql4_Abstract
{
	protected $_table;
	protected $_productEntityTable;
	protected $_productEntityVarchar;
	protected $_productEntityDecimal;

	public function _construct()
	{
		$this->_init('managecatalogspr/temp_price', 'id');
		$this->_table = $this->getTable('managecatalogspr/temp_price');
		$productEntity = Mage::getResourceModel('catalog/product');
		$this->_productEntityTable = $productEntity->getTable('catalog_product_entity');
		$this->_productEntityVarchar = $productEntity->getTable('catalog_product_entity_varchar');
		$this->_productEntityDecimal = $productEntity->getTable('catalog_product_entity_decimal');

	}
	public function getCountData($estatus='')
	{
		$select = $this->_getReadAdapter()->select()
		->from(array('main_table'=>$this->getTable('managecatalogspr/temp_price')),
		array('total'=>'count(id)'));
		if($estatus!='')
		$select->where('main_table.status in ('.$estatus.')');
		$res = $this->_getReadAdapter()->fetchAll($select);
		if(isset($res[0]['total'])) {
			return $res[0]['total'];
		}
	}
	public function loadDataOperation($file)
	{
		//windows path seperator
		$file = str_replace("\\","\\\\",$file); 
		$dbArray = $this->_getWriteAdapter()->getConfig();
		
		$connect=mysql_connect($dbArray['host'],$dbArray['username'],$dbArray['password']);
		if (!$connect) {
			die('Could not connect: ' . mysql_error());
		}
		$db_selected = mysql_select_db($dbArray['dbname'],$connect);
		if (!$db_selected) {
			die ('Database Not Connected : ' . mysql_error());
		}
		mysql_set_charset("utf8",$connect);
		mysql_query($dbArray['initStatements'],$connect);
		mysql_query("LOAD DATA INFILE 
                    '".$file."' 
                  REPLACE INTO TABLE {$this->getTable('managecatalogspr/temp_price')}
                  LINES TERMINATED BY '\r\n'
                 (`version`,`sku`,`catalogsku`,`upc_code`,`old_sku`,
                 `substitute_skus`,`complimentary_skus`,`catalogpage`,
                 `long_description`,`short_description`,`empty`,
                 `sales_copy`,`keywords`,`ej_image`,`et_image`,
                 `productblock_label`,`productblock_name`,`subclass_label`,
                 `subclass_name`,`class_label`,`class_name`,`department_label`,
                 `department_name`,`singlelevelindexlabel`,`Singlelevelindexname`,
                 `manufacturer_label`,`manufacturer_name`,`manufacturer_prefix`,
                 `minorityownedmanufacturer`,`recycled`,`postconsumerwaste`,
                 `msds_required`,`weight`,`oktoups`,`empty2`,`specialorder`,
                 `assembly_required`,`country`,`list_price`,`Qty`,`um`,`packinglevel1`,
                 `packinglevel2`,`empty3`,`custom`,`color`,`datedgood`,
                 `unspccode`,`schoolsupply`,`totalpercentagerecycledcontent`,
                 `barcodenumber`,`empty4`,`branchonly`,`masterdepartmentlabel`,
                 `masterdepartmentname`,`furniturecatalogsku`,`noreturns`)");
    	mysql_close($connect);
	}
	
    
	public function loadDataInfile($file)
	{
		try {
		    $con = $this->_getWriteAdapter();
           	$con->query("TRUNCATE TABLE {$this->getTable('managecatalogspr/temp_price')} ");
           
           //load data in to table
            $this->loadDataOperation($file);
		   	// trim space with SKU field

            $con->query("UPDATE {$this->getTable('managecatalogspr/temp_price')} AS p SET sku = TRIM(p.sku),list_price = (0.01 * p.list_price)");
            
           	// update is_in_stock
            $this->priceUpdate();
			$this->costUpdate();
            print "Price Update Successfully. \n";
		    
		}catch (Exception $e) {
			die($e->getMessage());
		}
	}
	
	public function reindexData()
     {
        // Reindex of Data
            print "Reindexing Start ....\n";
            $cmd="php indexer.php --reindex catalog_product_attribute,catalog_product_price,catalog_product_flat";
            system($cmd);
            print "Reindexing Completed\n";
            
     }
    
  	public function getConfigVal($field)
	{
		return Mage::getStoreConfig('managecatalogspr/price_file/'.$field);
	}
    public function getAttrributeId($code)
	{
		if($code) {
			$installer = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
			$attributeId = $installer->getAttributeId('catalog_product', $code);
			return $attributeId;
		}else return "";
	}
    Public function priceUpdate()
     {
      	   $con = $this->_getWriteAdapter();
           $per = $this->getConfigVal('price_markup_percent');
           $priceCode="price";
           $priceId=$this->getAttrributeId($priceCode);
           $con->query("UPDATE {$this->_productEntityTable} AS `cpe`
                        INNER JOIN {$this->_productEntityDecimal} AS `cped`
                        ON `cpe`.entity_id = `cped`.entity_id and `cped`.attribute_id = $priceId
                        inner join {$this->getTable('managecatalogspr/temp_price')} AS `tp` on `tp`.sku = `cpe`.sku
                        SET `cped`.value = `tp`.list_price * (1 + ($per/100))
                        where `tp`.sku = `cpe`.sku and `cpe`.entity_id = `cped`.entity_id and `cped`.attribute_id = $priceId ");
           
      }
      
     Public function costUpdate()
     {
      	   $con = $this->_getWriteAdapter();
           $costCode="cost";
           $costId=$this->getAttrributeId($costCode);
           $con->query("UPDATE {$this->_productEntityTable} AS `cpe`
                        INNER JOIN {$this->_productEntityDecimal} AS `cped`
                        ON `cpe`.entity_id = `cped`.entity_id and `cped`.attribute_id = $costId
                        inner join {$this->getTable('managecatalogspr/temp_price')} AS `tp` on `tp`.sku = `cpe`.sku
                        SET `cped`.value = `tp`.list_price 
                        where `tp`.sku = `cpe`.sku and `cpe`.entity_id = `cped`.entity_id and `cped`.attribute_id = $costId ");
           
      }
}